package org.chen.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.domain.entity.VideoGenerationRecord;
import org.chen.mapper.VideoGenerationRecordMapper;
import org.chen.service.TemplateService;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 视频处理任务调度器
 */
@Component
@EnableScheduling
@RequiredArgsConstructor
@Slf4j
public class VideoProcessingTaskScheduler {

    private final VideoGenerationRecordMapper recordMapper;
    private final TemplateService templateService;

    /**
     * 定期检查处理中的视频任务状态
     * 每30秒执行一次
     */
    @Scheduled(fixedRate = 30000)
    public void checkProcessingVideos() {
        log.debug("开始检查处理中的视频任务...");
        
        // 查询所有处理中的任务
        QueryWrapper<VideoGenerationRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "PROCESSING");
        List<VideoGenerationRecord> processingRecords = recordMapper.selectList(wrapper);
        
        // 检查每个任务的状态
        for (VideoGenerationRecord record : processingRecords) {
            try {
                log.debug("检查视频任务状态: {}", record.getId());
                templateService.checkVideoStatus(record.getId());
            } catch (Exception e) {
                log.error("检查视频任务状态失败: {}, 错误: {}", record.getId(), e.getMessage());
            }
        }
        
        log.debug("视频任务状态检查完成，共处理 {} 个任务", processingRecords.size());
    }
    
    /**
     * 清理旧的失败任务
     * 每天凌晨2点执行一次
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanupFailedTasks() {
        log.info("开始清理失败的视频任务...");
        
        // 这里可以添加清理逻辑，例如删除30天前的失败任务
        // 或者设置为自动重试等
    }
}